/*
 * @Author: lijing
 * @e-mail: 1413979079@qq.com
 * @LastEditors: lijing
 * @Date: 2019-10-09 16:40:05
 * @LastEditTime: 2020-05-15 12:09:59
 * @FilePath: \client\src\router\index.js
 * @Description: 封装所有路由，当路由增加到很多的时候可以将每个路由抽离出去当做单独的文件，比如用到二级路由的时候
 */

import Vue from 'vue'
import Router from 'vue-router'
import AdminRouter from './admin'
import store from "../store/index"

Vue.use(Router)

const router = new Router({
  // 路由模式：hash(默认)，history模式
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'MainPage',
      component: () => import('@/views/MainPage')
    },
    {
      path: '/post/:articleId',
      name: "ArticleDetails",
      component: () => import('@/views/ArticleDetails')
    },
    {
      path: "/archives",
      name: "Archives",
      component: () => import('@/views/Archives')
    },
    {
      path: "/message",
      name: "LeaveMessage",
      component: () => import('@/views/LeaveMessage')
    },
    {
      path: "/about",
      name: "AboutMe",
      component: () => import('@/views/AboutMe')
    },
    {
      path: "/websites",
      name: "Websites",
      component: () => import('@/views/Websites')
    },
    {
      path: '/init',
      component: () => import('@/views/Init.vue'),
      children: [
        {
          path: "user",
          name: "InitUser",
          component: () => import('@/views/admin/InitUser.vue')
        },
        {
          path: "blog",
          name: "InitBlog",
          component: () => import('@/views/admin/InitBlog.vue')
        },
        {
          path: "profile",
          name: "InitProfile",
          component: () => import('@/views/admin/InitProfile.vue')
        },
      ]
    },
    AdminRouter,
    {
      path: '/error404',
      name: "Error404",
      component: () => import('@/views/error/Error404')
    },
    {
      path: '/error500',
      name: "Error500",
      component: () => import('@/views/error/Error500')
    },
    {
      path: '/*',
      redirect: '/error404'
    }
  ]
})

router.beforeEach((to, from, next) => {
  let toPath = to.path;
  if (toPath.startsWith('/admin') && toPath != '/admin/login') {
    if (store.state.app.adminToken) {
      next();
    } else {
      next("/admin/login");
    }
  } else {
    next();
  }
})

export default router;
